package com.sniper.serviceribbon.hystrix;

import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.HystrixCollapserProperties;
import com.netflix.hystrix.HystrixCommand;
import com.sniper.model.LineShop;
import com.sniper.serviceribbon.service.LineShopService;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import static com.netflix.hystrix.HystrixCollapserKey.Factory.asKey;

/**
 * 请求合并
 *
 * @author suzhen
 * @create 2018/3/15
 */
public class LineShopCollapseCommand extends HystrixCollapser<List<LineShop>, LineShop, String> {

    private LineShopService lineShopService;
    private String id;

    public LineShopCollapseCommand(LineShopService lineShopService, String id) {
        super(Setter
                .withCollapserKey(asKey("lineShopCollapseCommand"))
                .andCollapserPropertiesDefaults(
                        HystrixCollapserProperties.Setter()
                                .withTimerDelayInMilliseconds(2000)
                ));
        this.lineShopService = lineShopService;
        this.id = id;
    }

    @Override
    public String getRequestArgument() {
        return id;
    }

    @Override
    protected HystrixCommand<List<LineShop>> createCommand(Collection<CollapsedRequest<LineShop, String>> collection) {

        List<String> ids = new ArrayList<>(collection.size());
        ids.addAll(collection.stream().map(CollapsedRequest::getArgument).collect(Collectors.toList()));
        return new LineShopBatchCommand(lineShopService, ids);
    }

    @Override
    protected void mapResponseToRequests(List<LineShop> lineShops, Collection<CollapsedRequest<LineShop, String>> collection) {
        int count = 0;
        for (CollapsedRequest<LineShop, String> collapsedRequest : collection) {
            LineShop lineShop = lineShops.get(count++);
            collapsedRequest.setResponse(lineShop);
        }
    }
}